﻿/*
 * menuItemTab  名称 tab_ 前缀
 * menuItemColumn 名称 column 前缀
 */

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Data;
using System.Drawing;
using System.ComponentModel;
using System.Diagnostics;

using BrightIdeasSoftware;

using FCNS;
using FCNS.Controls.Calendars;
using FCNS.Native;
using FCNS.Utility;

using FCNS.KeepMoney.Util;
using FCNS.KeepMoney.UI;
using FCNS.KeepMoney.Data;
using FCNS.KeepMoneyLibrary.Data;
using FCNS.KeepMoneyLibrary.Util;
using FCNS.KeepMoney.Configuration;
using FCNS.KeepMoney.Plugins;

namespace FCNS.KeepMoney.Forms
{
    public partial class MainForm
    {
        #region 变量
        private KMData kmData;

        AceMoney configMoney = Program.AppConfig.Money;
        AceGtd configGtd = Program.AppConfig.Gtd;
        AceApplication configApp = Program.AppConfig.App;
        AceChart configPlot = Program.AppConfig.Charts;
        AceMainForm configMainForm = Program.AppConfig.MainForm;
        AceChart configChart = Program.AppConfig.Charts;
        AceBill configBill = Program.AppConfig.Bill;

        List<EntryField> entryField;
        List<GroupField> groupField;
        List<BankField> bankField;

        bool showForm = true;
        Timer adsenseTimer = new Timer();
        PluginManager pluginManager = new PluginManager();
        //TreeNode recycleBin = new TreeNode(LanguageUtil.回收站, 0, 0);
        public ToolStripItemCollection TheGroupMenu, TheEntryMenu, TheGtdEntryMenu, TheAdditionMenu;

        IGtdView gtdView;

        #endregion

        protected override void WndProc(ref Message m)
        {
            base.WndProc(ref m);
            switch (m.WParam.ToInt32())
            {
                case 1382408:
                    toolMenuNewEntry.PerformClick();
                    break;
                case 1382409:
                    this.Show();
                    this.BringToFront();
                    break;
            }
        }

        #region 初始化、填充控件
        private void InitControlsWhenApplicationStart()
        {
            if (configMainForm.Maximized)
                this.WindowState = FormWindowState.Maximized;
            else
            {
                this.Size = new Size(configMainForm.Width, configMainForm.Height);
                this.Location = new Point(configMainForm.X, configMainForm.Y);
                if (this.Left < 5 || this.Top < 5)
                    this.Location = new Point(10, 10);
            }

            //菜单
            InitAdditionMenu();
            InitGroupMenu();
            InitEntryMenu();
            InitGtdEntryMenu();
            ReadFileOpenRecord();

            menuViewDisplaySubGroupEntry.Checked = configMainForm.ShowSubGroupEntry;
            menuViewShowOverdueData.Checked = configApp.ShowOverdueData;
            menuViewDisplayGroups.Checked = configMainForm.DisplayGroups;
            menuViewDisplayMiniForm.Checked = configMainForm.BusinessCardOverlay;
            ((ToolStripMenuItem)menuViewHotItemStyle.DropDownItems["hotItemStyle" + configMainForm.HotItemStyle.ToString()]).Checked = true;

            treeViewExGroup.ImageList = Program.ImagesList;

            ConfigListViewEntrysAndMenuItemColumn(null);

            listViewEntry.UseAlternatingBackColors = configMainForm.EntryUseBackColor;
            listViewEntry.AlternateRowBackColor = Color.FromArgb(configMainForm.AlternateRowBackColor);
            listViewEntry.GridLines = configMainForm.GridLine;

            ListViewDisplayGroups();

            HotItemStyleUtil.SetHotItemStyle(listViewEntry, configMainForm.BusinessCardOverlay);

            toolMenuIncome.ForeColor = Color.FromArgb(configMoney.PlusColor);
            toolMenuExpense.ForeColor = Color.FromArgb(configMoney.MinusColor);
            toolMenuNormal.Margin = new Padding(panelLeft.Width - 60, 0, 0, 0);

            //不要修改以下几项顺序
            comboBoxSearch.Items.Add(LanguageUtil.最近账单日);
            comboBoxSearch.Items.Add(LanguageUtil.最近一个月);
            comboBoxSearch.Items.Add(LanguageUtil.最近一个星期);
            comboBoxSearch.Items.Add(LanguageUtil.逾期账务);
            //comboBoxSearch.Items.Add(LanguageUtil.定期账务);//default


            numericUpDownEntryMoney.DecimalPlaces = configMoney.DecimalPlaces;

            //gtd
            //if (!configGtd.DefaultStyle)
            //{
            //gtdView = new GtdViewMac();
            //splitContainer1.Panel1.Controls.Add((GtdViewMac)gtdView);
            //((GtdViewMac)gtdView).Dock = DockStyle.Fill;
            //((GtdViewMac)gtdView).ContextMenuStrip = contextMenuStripEntry;
            //}
            //else
            //{
            gtdView = new GtdViewDefault();
            splitContainerCenter.Panel1.Controls.Add((GtdViewDefault)gtdView);
            ((GtdViewDefault)gtdView).Dock = DockStyle.Fill;
            ((GtdViewDefault)gtdView).ChangedTask += new GtdViewDefault.ChangedTaskD(OnGtdViewDefaultChangedTask);
            //}

            // UpdateUI_GtdMenu();
            listViewGtd1.OnSelectedChanged += new System.EventHandler(this.OnGtdGroupSelectedChanged);

            //图表
            chartPanel1.ChartAreas["Default"].Area3DStyle.Enable3D = configChart.Enable3D;
            chartPanel2.ChartAreas["Default"].Area3DStyle.Enable3D = configChart.Enable3D;
            chartPanel1.ChartAreas["Default"].AxisX.IsMarginVisible = true;
            chartPanel2.ChartAreas["Default"].AxisX.IsMarginVisible = true;
            chartPanel1.ChartAreas["Default"].Area3DStyle.IsClustered = true;

            chartPanel1.ChartAreas["Default"].Area3DStyle.PointDepth = configChart.Enable3D ?
                Program.AppConfig.Charts.PointDepth : 0;
            chartPanel2.ChartAreas["Default"].Area3DStyle.PointDepth = configChart.Enable3D ?
                Program.AppConfig.Charts.PointDepth : 0;
            chartPanel1.ChartAreas["Default"].Area3DStyle.PointGapDepth = configChart.Enable3D ?
                Program.AppConfig.Charts.GapDepth : 0;
            chartPanel2.ChartAreas["Default"].Area3DStyle.PointGapDepth = configChart.Enable3D ?
                Program.AppConfig.Charts.GapDepth : 0;
        }

        private void InitMoney()
        {
            toolMenuMode.Text = "Money";
            toolMenuFilter.Visible = true;
            toolMenuImport.Enabled = true;

            treeViewExGroup.Dock = DockStyle.Fill;
            listViewEntry.Dock = DockStyle.Fill;

            gtdView.Visible = false;
            listViewGtd1.Visible = false;

            treeViewExGroup.Visible = true;
            listViewEntry.Visible = true;

            panelRight.Visible = true;

            splitContainerCenter.Panel2Collapsed = false;
        }


        private void ConfigControlsWhenOpenKMDfile(string file)
        {
            groupField = GroupField.GetGroupField;
            bankField = BankField.GetBankField;
            entryField = EntryField.GetEntryField;

            ShowGroupField();

            ReLoadEntry();

            string mainFormText = configMainForm.DisplaysTheFilePathInTheMainFormText ? " - " + file : " 免费、简单、开源的个人理财软件";
            this.Text = AppDefines.fullName + mainFormText;

            UpdateUI(UIState.OpenKMD);
        }

        private void ShowGroupField()
        {
            treeViewExGroup.SuspendLayout();
            treeViewExGroup.Nodes.Clear();

            foreach (GroupField gf in groupField.FindAll(gf => { return gf.ParentGroupId == 0; }))
            {
                TreeNode node = new TreeNode(gf.Name);
                node.Tag = gf;
                node.ImageIndex = node.SelectedImageIndex = gf.IconIndex;
                node.ToolTipText = gf.Note;

                List<GroupField> fields = groupField.FindAll(gf2 => { return gf2.ParentGroupId == gf.Id; });
                if (fields != null)
                    ShowSubGroupField(node, fields);

                treeViewExGroup.Nodes.Add(node);
            }

            treeViewExGroup.ExpandAll();
            treeViewExGroup.ResumeLayout();

            if (configApp.FileOpenRecords.Count > 0)
            {
                foreach (TreeNode node in treeViewExGroup.Nodes)
                    if (treeViewExGroup.SelectedNode != null)
                        return;
                    else
                        SetSelectedNode(node);
            }
            if (treeViewExGroup.SelectedNode == null)//如果上面无法找到节点,程序会异常
                treeViewExGroup.SelectedNode = treeViewExGroup.Nodes[0];

            Debug.Assert(treeViewExGroup.SelectedNode != null, "ShowGroupField");
        }

        private void ShowSubGroupField(TreeNode node, List<GroupField> fields)
        {
            foreach (GroupField gf in fields)
            {
                TreeNode node2 = new TreeNode(gf.Name);
                node2.Tag = gf;
                node2.ImageIndex = node2.SelectedImageIndex = gf.IconIndex;
                node2.ToolTipText = gf.Note;

                List<GroupField> fields2 = groupField.FindAll(gf2 => { return gf2.ParentGroupId == gf.Id; });
                if (fields2 != null)
                    ShowSubGroupField(node2, fields2);

                node.Nodes.Add(node2);
            }
        }

        private void SetSelectedNode(TreeNode node)
        {
            if (((GroupField)node.Tag).Id == configApp.FileOpenRecords[0].LastSelectedGroupId)
                treeViewExGroup.SelectedNode = node;
            else
                foreach (TreeNode n in node.Nodes)
                    SetSelectedNode(n);
        }

        private void ShowEntryData()
        {
            if (treeViewExGroup.SelectedNode == null)
                return;

            listViewEntry.SuspendLayout();

            int groupId = ((GroupField)treeViewExGroup.SelectedNode.Tag).Id;
            List<EntryField> fields = new List<EntryField>(entryField.FindAll(ef => { return ef.GroupId == groupId; }));
            if (configMainForm.ShowSubGroupEntry)
                foreach (int id in GroupField.GetAllSubGroupIds(groupId))
                    fields.AddRange(entryField.FindAll(ef => { return ef.GroupId == id; }));

            if (!configApp.ShowOverdueData)
                fields.RemoveAll(ef => { return ef.Date.Month != Program.YearShown.Month; });

            foreach (BankField bf in bankField)
                if (!bf.Visible)
                    fields.RemoveAll(ef => { return ef.BankId == bf.Id; });

            listViewEntry.SetObjects(fields);
            listViewEntry.ResumeLayout();
        }
        #endregion

        private void SaveConfig()
        {
            foreach (ColumnHeader c in listViewEntry.Columns)
            {
                ((AceColumn)c.Tag).ColumnIndex = c.DisplayIndex;
                ((AceColumn)c.Tag).Width = c.Width;
            }

            AppSerializer.SaveConfig(Program.AppConfig);
        }

        #region 菜单和账务记录列

        private void InitAdditionMenu()
        {
            TheAdditionMenu = new ToolStripItemCollection(contextMenuStripMain, new ToolStripItem[] { });
            TheAdditionMenu.Add(new ToolStripSeparator());

            ToolStripMenuItem exportData = new ToolStripMenuItem("数据导出");
            exportData.Name = "ExportData";
            exportData.Image = Properties.Resources.export_32;
            exportData.Click += new EventHandler(OnExportData);
            exportData.ImageScaling = ToolStripItemImageScaling.None;

            TheAdditionMenu.Add(exportData);
        }

        private void InitGroupMenu()
        {
            TheGroupMenu = new ToolStripItemCollection(contextMenuStripGroup, new ToolStripItem[] { });

            ToolStripMenuItem NewGroup = new ToolStripMenuItem(LanguageUtil.添加群组);
            NewGroup.Name = "contextMenuItemNewGroup";
            NewGroup.Image = Properties.Resources.groupN32;
            NewGroup.Click += new System.EventHandler(OnNewGroup);

            ToolStripMenuItem EditGroup = new ToolStripMenuItem(LanguageUtil.编辑群组);
            EditGroup.Name = "contextMenuItemEditGroup";
            EditGroup.Image = Properties.Resources.groupE32;
            EditGroup.Click += new System.EventHandler(OnEditGroup);

            ToolStripMenuItem DeleteGroup = new ToolStripMenuItem(LanguageUtil.删除群组);
            DeleteGroup.Name = "contextMenuItemDeleteGroup";
            DeleteGroup.Image = Properties.Resources.groupD4;
            DeleteGroup.Click += new System.EventHandler(OnDeleteGroup);

            TheGroupMenu.AddRange(new ToolStripItem[] { NewGroup, EditGroup, DeleteGroup });
            foreach (ToolStripItem i in TheGroupMenu)
                if (i is ToolStripMenuItem)
                    i.ImageScaling = ToolStripItemImageScaling.None;
        }

        ToolStripMenuItem menuRemoveAlertDate;
        ToolStripMenuItem menuTags;

        private void InitEntryMenu()
        {
            TheEntryMenu = new ToolStripItemCollection(contextMenuStripEntry, new ToolStripItem[] { });

            ToolStripMenuItem NewEntry = new ToolStripMenuItem(LanguageUtil.添加记录);
            NewEntry.Name = "NewEntry";
            NewEntry.Image = Properties.Resources.entryN32;
            NewEntry.Click += new System.EventHandler(OnNewEntryInMenu);

            ToolStripMenuItem EditEntry = new ToolStripMenuItem(LanguageUtil.编辑查看记录);
            EditEntry.Name = "EditEntry";
            EditEntry.Image = Properties.Resources.entryE24;
            EditEntry.Click += new System.EventHandler(OnEditEntry);

            ToolStripMenuItem DeleteEntry = new ToolStripMenuItem(LanguageUtil.删除记录);
            DeleteEntry.Name = "DeleteEntry";
            DeleteEntry.Image = Properties.Resources.entryD32;
            DeleteEntry.Click += new System.EventHandler(OnDeleteEntry);

            ToolStripSeparator t1 = new ToolStripSeparator();

            menuTags = new ToolStripMenuItem(LanguageUtil.标记);
            menuTags.Name = "Tags";
            menuTags.DropDownOpening += new EventHandler(Tags_DropDownOpening);
            menuTags.DropDownItemClicked += new ToolStripItemClickedEventHandler(Tags_DropDownItemClicked);

            ToolStripMenuItem AddTag = new ToolStripMenuItem(LanguageUtil.添加标记);
            AddTag.Name = "AddTag";
            AddTag.DropDownItemClicked += new ToolStripItemClickedEventHandler(AddTag_DropDownItemClicked);

            ToolStripMenuItem NewTag = new ToolStripMenuItem(LanguageUtil.新增标记);
            NewTag.Name = "NewTag";

            ToolStripSeparator t2 = new ToolStripSeparator();

            ToolStripMenuItem NewTag1 = new ToolStripMenuItem(LanguageUtil.借款);
            ToolStripMenuItem NewTag2 = new ToolStripMenuItem(LanguageUtil.贷款);

            AddTag.DropDownItems.AddRange(new ToolStripItem[] { NewTag, t2 });
            AddTag.DropDownItems.Add(LanguageUtil.借款);
            AddTag.DropDownItems.Add(LanguageUtil.贷款);

            ToolStripMenuItem DeleteTag = new ToolStripMenuItem(LanguageUtil.移除标记);
            DeleteTag.Name = "DeleteTag";
            DeleteTag.DropDownItemClicked += new ToolStripItemClickedEventHandler(DeleteTag_DropDownItemClicked);

            ToolStripSeparator t3 = new ToolStripSeparator();

            menuTags.DropDownItems.AddRange(new ToolStripItem[] { AddTag, DeleteTag, t3, NewTag1, NewTag2 });


            ToolStripSeparator t4 = new ToolStripSeparator();

            menuRemoveAlertDate = new ToolStripMenuItem(LanguageUtil.移除提醒);
            menuRemoveAlertDate.Name = "RemoveAlertDate";
            menuRemoveAlertDate.Image = Properties.Resources.alert_32;
            menuRemoveAlertDate.Click += new EventHandler(OnRemoveAlertDate);

            TheEntryMenu.AddRange(new ToolStripItem[] { NewEntry, EditEntry, DeleteEntry, t1, menuTags, t4, menuRemoveAlertDate });
            foreach (ToolStripItem i in TheEntryMenu)
                if (i is ToolStripMenuItem)
                    i.ImageScaling = ToolStripItemImageScaling.None;

        }

        private void InitGtdEntryMenu()
        {
            TheGtdEntryMenu = new ToolStripItemCollection(contextMenuStripGroup, new ToolStripItem[] { });
            //ToolStripMenuItem gtdDay = new ToolStripMenuItem(LanguageUtil.按日查看);
            //gtdDay.Name = "menuItemGtdDay";
            //gtdDay.Click += new System.EventHandler(OnGtdViewStyleChanged);

            //ToolStripMenuItem gtdWeek = new ToolStripMenuItem(LanguageUtil.按周查看);
            //gtdWeek.Name = "menuItemGtdWeek";
            //gtdWeek.Click += new System.EventHandler(OnGtdViewStyleChanged);

            //ToolStripMenuItem gtdMonth = new ToolStripMenuItem(LanguageUtil.按月查看);
            //gtdMonth.Name = "menuItemGtdMonth";
            //gtdMonth.Click += new System.EventHandler(OnGtdViewStyleChanged);

            ToolStripMenuItem gtdLevel = new ToolStripMenuItem(LanguageUtil.按优先级排序);
            gtdLevel.Name = "menuItemGtdLevel";
            gtdLevel.Click += new EventHandler(gtdSort_Click);

            ToolStripMenuItem gtdEndDate = new ToolStripMenuItem(LanguageUtil.按日期排序);
            gtdEndDate.Name = "menuItemGtdEndDate";
            gtdEndDate.Click += new EventHandler(gtdSort_Click);

            TheGtdEntryMenu.AddRange(new ToolStripItem[] { gtdLevel, gtdEndDate });
        }

        private void ConfigListViewEntrysAndMenuItemColumn(ToolStripMenuItem item)
        {
            if (item != null)
            {
                AceColumn ac = (AceColumn)item.Tag;
                ac.Show = !item.Checked;
                if (item.Checked)
                    listViewEntry.Columns.RemoveByKey(ac.ColumnName);
                else
                    AddListViewEntryColumn(ac);

                ShowEntryData();
            }
            else
            {
                configMainForm.ListViewEntryColumns.Sort(Compare);
                foreach (AceColumn ac in configMainForm.ListViewEntryColumns)
                {
                    string str = ac.GetDisplayName();
                    ToolStripMenuItem it = new ToolStripMenuItem(str);
                    it.Name = "column" + ac.Type.ToString();
                    it.Tag = ac;
                    ac.ColumnName = it.Name;
                    it.CheckOnClick = true;
                    menuViewEntryColumn.DropDownItems.Add(it);
                    if (ac.Show)
                    {
                        it.Checked = true;
                        AddListViewEntryColumn(ac);
                    }
                }

                //foreach (AceColumn ac in configMainForm.ListViewEntryColumns)
                //{
                //    if (ac.Show)
                //    {
                //        ((ToolStripMenuItem)menuViewEntryColumn.DropDownItems[ac.ColumnName]).Checked = true;
                //        AddListViewEntryColumn(ac);
                //    }
                //}
            }
            //if (listViewEntry.Columns["columnMoney"] != null)
            //    listViewEntry.Columns["columnMoney"].TextAlign = HorizontalAlignment.Right;
        }

        private int Compare(AceColumn ac1, AceColumn ac2)
        {
            return ac1.ColumnIndex.CompareTo(ac2.ColumnIndex);
        }

        private void AddListViewEntryColumn(AceColumn ac)
        {
            OLVColumn column = new OLVColumn(ac.GetDisplayName(), ac.ColumnName);
            column.TextAlign = AceColumn.GetTextAlign(ac.Type);
            column.Name = ac.ColumnName;
            column.Searchable = true;
            column.Width = ac.Width;
            column.Tag = ac;
            listViewEntry.Columns.Add(column);
        }
        #endregion

        private void ChangeMainFormStatus()
        {
            showForm = !showForm;
            if (showForm)
            {
                if (configMainForm.MinimizeToTray && !configMainForm.ShowInTaskBarAndTray)
                {
                    this.Show();
                    return;
                }
                this.WindowState = FormWindowState.Normal;
            }
            else
            {
                if (configMainForm.MinimizeToTray && !configMainForm.ShowInTaskBarAndTray)
                {
                    this.Hide();
                    return;
                }
                this.WindowState = FormWindowState.Minimized;
            }
        }

        private bool IsSuccessfullyOpenTheKMDfile(string file)
        {
            if (!File.Exists(file))
            {
                MessageBox.Show(LanguageUtil.文件无法访问_可能文件已移除);
                return false;
            }

            kmData = new KMData(file, false);

            bool hasAuthorized;
            DisplayTheLoginForm(LoginFormState.Login, out hasAuthorized);
            if (!hasAuthorized)
                return false;

            WriteFileOpenRecord(file);
            foreach (RegularEntryField r in RegularEntryField.GetRegularEntryField)
                r.CalcRegular();


            ConfigControlsWhenOpenKMDfile(file);
            ConfigureAlertMessage();

            return true;
        }

        private void WriteFileOpenRecord(string lastestFile)
        {
            //仅保存最近 5 个记录
            if (lastestFile == null)
            {
                if (treeViewExGroup.SelectedNode != null)
                    configApp.FileOpenRecords[0].LastSelectedGroupId = ((GroupField)treeViewExGroup.SelectedNode.Tag).Id;

                return;
            }

            ProgramUtil.UpdateFileOpenRecord(lastestFile);
            ReadFileOpenRecord();
        }

        private void ReadFileOpenRecord()
        {
            while (menuFileOpen.DropDownItems.Count > 3)
                menuFileOpen.DropDownItems.RemoveAt(3);

            foreach (AceFileOpenRecord str in configApp.FileOpenRecords)
                menuFileOpen.DropDownItems.Add(str.FilePath, null, FileOpenRecord_Click);
        }

        private void ConfigureAlertMessage()
        {
            if (!configApp.EnablAlertMessage)
                return;

            //StringBuilder sb = new StringBuilder();
            ////账单日提醒
            //if (configBill.LatestBillingMonth != DateTime.Now.AddMonths(-1).Month)
            //{
            //    sb.Append(Program.YearShown.AddMonths(-1).ToString("yyyy-MM") +
            //         Program.Translation.ApplyTo("账单已经生成."));

            //    toolMenuAlert.Visible = true;
            //}
            //提醒
            //List<EntryField> fields = entryField.FindAll(ef => { return (DateTime)ef.AlertDate < DateTime.Now; });
            //if (fields.Count == 0)
            //    return;

            //if (toolMenuAlert.Visible)
            //{
            //    if (File.Exists(AppDefines.msgVoice))
            //    {
            //        Mp3Player p = new Mp3Player();
            //        p.FileName = AppDefines.msgVoice;
            //        p.play();
            //    }
            //}
            //toolMenuAlert.Tag = fields;
        }

        private void PrintEntryList(ListView listView)
        {
            PrintForm p = new PrintForm();
            p.Init(listView, LanguageUtil.收支明细, AppDefines.kmoneyInstructions, "", 0);
            p.Show(this);
        }

        private void DisplayTheLoginForm(LoginFormState loginFormState, out bool hasAuthorized)
        {
            hasAuthorized = true;
            LoginForm l = new LoginForm();

            switch (loginFormState)
            {
                case LoginFormState.Login:
                    if (configApp.DisplayTheLoginForm)
                    {
                        l.TopMost = true;
                        if (l.ShowDialog() != DialogResult.OK)
                            hasAuthorized = false;
                    }
                    break;

                case LoginFormState.ChangePwd:
                    l.ChangePwd = true;
                    l.Show(this);
                    break;

                case LoginFormState.Lock:
                    l.LockForm = true;
                    this.Visible = false;
                    notifyMenuItemLine.Visible = false;
                    notifyMenuItemNewEntry.Visible = false;
                    l.ShowDialog();
                    this.Visible = true;
                    notifyMenuItemLine.Visible = true;
                    notifyMenuItemNewEntry.Visible = true;
                    break;
            }
        }

        private string GetNewKMDfilePath(KMDformat format)//alert  优化
        {
            string str = string.Empty;
            using (SaveFileDialog sfd = new SaveFileDialog())
            {
                sfd.InitialDirectory = AppDefines.appPath;
                if (format == KMDformat.CSV)
                {
                    sfd.Filter = "CSV(*.csv)|*.csv";
                    sfd.FileName = "kmd_csv";
                }
                else
                {
                    sfd.Filter = AppDefines.kmdFilter;
                    sfd.FileName = LanguageUtil.新建数据库;
                }
                if (sfd.ShowDialog() == DialogResult.OK)
                    str = sfd.FileName;
            }
            return str;
        }

        private void ListViewDisplayGroups()//alert 有什么意义?
        {
            if (listViewEntry.Columns.Count == 0)//这是有可能发生的
                return;

            listViewEntry.ShowGroups = configMainForm.DisplayGroups;
            if (!listViewEntry.ShowGroups)
                return;

            AceColumn column = null;
            foreach (AceColumn ac in configMainForm.ListViewEntryColumns)
            {
                if (ac.Sort)
                {
                    column = ac;
                    break;
                }
            }

            if (column != null)
                listViewEntry.PrimarySortColumn = (OLVColumn)listViewEntry.Columns[column.ColumnName];
            else
                listViewEntry.PrimarySortColumn = (OLVColumn)listViewEntry.Columns[0];

            listViewEntry.BuildList();
        }

        private EntryField GetSelectedEntry()
        {
            EntryField field = null;

            if (listViewEntry.SelectedObject != null)
            {
                field = (EntryField)listViewEntry.SelectedObject;

                if (field.EntryType == KMDEntryType.Regular)
                {
                    MessageBox.Show(LanguageUtil.定期账务_无法于当前窗体编辑);
                    return null;
                }
                if (field.EntryType == KMDEntryType.BankHasExpired)
                {
                    MessageBox.Show(LanguageUtil.所属钱袋已禁用_请在钱袋配置中更改);
                    return null;
                }
                if (configBill.LockBill && field.Date <= Program.YearShown.AddMonths(-1))
                {
                    MessageBox.Show(LanguageUtil.无法修改删除已出账单的记录_请在选项中更改配置);
                    field = null;
                }
            }

            return field;
        }

        /// <summary>
        /// 重新统计并绘制 Entry 列表,图表,合计统计
        /// </summary>
        public void ReLoadEntry()
        {
            if (configMainForm.UItype == UiType.Money)
            {
                ShowEntryData();
                UpdateToolBarBottom();
            }
            else
                ShowGtd();
        }

        private void ApplyTranslate()
        {
            Program.Translation.ApplyTo(this);
            Program.Translation.ApplyTo("FCNS.KeepMoney.Forms.contextMenuStripMain", contextMenuStripMain.Items);
            Program.Translation.ApplyTo("FCNS.KeepMoney.Forms.contextMenuStripNotify", contextMenuStripNotify.Items);
            Program.Translation.ApplyTo("FCNS.KeepMoney.Forms.toolStripTop", toolStripTop.Items);
            Program.Translation.ApplyTo("FCNS.KeepMoney.Forms.toolStripBottom", toolStripBottom.Items);
        }

        #region 更新控件与菜单
        public void UpdateUI(UIState state)
        {
            switch (state)
            {
                case UIState.DataHasBeenChanged:
                    UpdateUI_DataHasBeenChanged();
                    break;

                case UIState.ConfigBankMenu:
                    UpdateUI_ConfigBankMenu();
                    break;

                case UIState.ConfigEditMenu:
                    UpdateUI_ConfigEditMenu();
                    break;

                case UIState.OpenKMD:
                    UpdateUI_OpenKMD();
                    break;

                case UIState.Init:
                    UpdateUI_Init();
                    UpdateToolBarBottom();
                    break;
            }
        }

        private void UpdateUI_GtdMenu()
        {
            if (gtdView is GtdViewDefault)
            {
                ((ToolStripMenuItem)(TheGtdEntryMenu[3])).Checked = !configGtd.SortByDate;
                ((ToolStripMenuItem)(TheGtdEntryMenu[4])).Checked = configGtd.SortByDate;
            }
            else
                for (int i = 0; i < 3; i++)
                    ((ToolStripMenuItem)(TheGtdEntryMenu[i])).Checked = (i == (int)configGtd.CalendarStyle);

            gtdView.UpdateGtdView(true);
        }

        private void UpdateUI_DataHasBeenChanged()
        {
            Program.SaveKMD = true;

            switch (configMainForm.UItype)
            {
                case UiType.Gtd:
                    listViewGtd1.UpdateList();
                    gtdView.UpdateGtdView(true);
                    break;

                case UiType.Money://alert 优化
                    ShowEntryData();
                    UpdateChart(configChart.DefaultChart);
                    UpdateToolBarBottom();
                    break;
            }
        }

        private void UpdateUI_ConfigBankMenu()
        {
            menuViewPurseColumn.DropDownItems.Clear();
            comboBoxPurse.Items.Clear();

            foreach (BankField bf in bankField)
            {
                ToolStripMenuItem item = new ToolStripMenuItem(bf.Name);
                item.Tag = bf;

                if (bf.Default)
                    item.Text += " - (" + LanguageUtil.默认 + ")";

                item.Checked = bf.Visible;
                item.CheckOnClick = true;
                menuViewPurseColumn.DropDownItems.Add(item);

                if (bf.Enable)
                    comboBoxPurse.Items.Add(item.Text);

                if (bf.Default)
                    comboBoxPurse.SelectedIndex = comboBoxPurse.Items.Count - 1;
            }
            Debug.Assert(comboBoxPurse.SelectedIndex > -1, "FCNS.KeepMoney.Forms.MainForm.UpdateUI_ConfigBankMenu");
        }

        private void UpdateUI_ConfigEditMenu()
        {
            bool editGroup = false, newEntry = false, editEntry = false, removeAlert = false, newTag = false, removeTag = false, tag = false; ;

            switch (configMainForm.UItype)
            {
                case UiType.Gtd:
                    if (listViewGtd1.Items.Count > 0)
                        editGroup = true;
                    break;


                case UiType.Money:
                    tag = true;
                    newEntry = editGroup = treeViewExGroup.SelectedNode != null;
                    EntryField field = (EntryField)listViewEntry.SelectedObject;
                    if (field != null)
                    {
                        editEntry = true;
                        newTag = true;
                        if (field.columnTag != string.Empty)
                            removeTag = true;

                        if (field.columnAlertDate != string.Empty)
                            removeAlert = true;
                    }
                    break;
            }
            TheGroupMenu[1].Enabled = editGroup;
            TheGroupMenu[2].Enabled = editGroup;

            TheEntryMenu[0].Enabled = newEntry;
            TheEntryMenu[1].Enabled = editEntry;
            TheEntryMenu[2].Enabled = editEntry;

            menuTags.DropDownItems[0].Enabled = newTag;
            menuTags.DropDownItems[1].Enabled = removeTag;
            menuRemoveAlertDate.Enabled = removeAlert;
            menuTags.Enabled = tag;
        }

        private void UpdateUI_OpenKMD()
        {
            toolMenuMode.Enabled = true;
            toolMenuNewEntry.Enabled = true;
            toolMenuScan.Enabled = true;
            toolMenuImport.Enabled = true;
            toolMenuPrint.Enabled = true;

            toolMenuLine.Enabled = true;
            toolMenuHistogram.Enabled = true;
            toolMenuPie.Enabled = true;
            toolMenuNormal.Enabled = true;

            menuData.Visible = true;
            menuView.Visible = true;
            menuEdit.Visible = true;

            menuToolMaintain.Visible = true;

            menuFileCloseKMD.Enabled = true;
            if (configApp.DisplayTheLoginForm)
            {
                menuFileLock.Enabled = true;
                menuFileChangePwd.Enabled = true;
            }

            menuFileSaveAs.Enabled = true;

            notifyMenuItemLine.Visible = true;
            notifyMenuItemNewEntry.Visible = true;

            // treeViewExGroup.ExpandAll();

            UpdateUI(UIState.ConfigBankMenu);

            splitContainerCenter.Visible = true;
            splitContainerLeft.Visible = true;
            panelLeft.Visible = true;

            if (configMainForm.UItype == UiType.Money)
                InitMoney();
            else
                InitGtd();

            UpdateChart(configChart.DefaultChart);
        }

        private void UpdateUI_Init()
        {
            menuFileLock.Enabled = false;
            menuFileSaveAs.Enabled = false;
            menuFileCloseKMD.Enabled = false;
            menuFileChangePwd.Enabled = false;

            toolMenuMode.Enabled = false;
            toolMenuSave.Enabled = false;
            toolMenuPrint.Enabled = false;
            toolMenuNewEntry.Enabled = false;
            toolMenuImport.Enabled = false;
            toolMenuScan.Enabled = false;

            toolMenuFilter.Visible = false;

            toolMenuAlert.Visible = false;
            toolMenuLine.Enabled = false;
            toolMenuHistogram.Enabled = false;
            toolMenuPie.Enabled = false;
            toolMenuNormal.Enabled = false;


            menuData.Visible = false;
            menuView.Visible = false;
            menuEdit.Visible = false;

            menuToolMaintain.Visible = false;

            notifyMenuItemLine.Visible = false;
            notifyMenuItemNewEntry.Visible = false;

            splitContainerCenter.Visible = false;
            splitContainerLeft.Visible = false;
            panelLeft.Visible = false;
            panelRight.Visible = false;
        }

        private void UpdateToolBarBottom()
        {
            decimal globalBalance = HealthStatusUtil.GlobalIncome + HealthStatusUtil.GlobalExpense;

            toolMenuIncome.Text = HealthStatusUtil.GlobalIncome.ToString();
            toolMenuExpense.Text = HealthStatusUtil.GlobalExpense.ToString();
            toolMenuBalance.Text = (HealthStatusUtil.GlobalIncome + HealthStatusUtil.GlobalExpense).ToString();
            toolMenuBalance.ForeColor = (globalBalance < 0) ? Color.FromArgb(configMoney.MinusColor) :
              Color.FromArgb(configMoney.PlusColor);

            HealthStatusUtil.Level level = HealthStatusUtil.GetStatus();
          //  toolStripLabelLevel.Text = level.ToString();
            switch (level)
            {
                case HealthStatusUtil.Level.A:
                    toolStripLabelLevel.Image = Properties.Resources.level_A_32;
                    break;
                case HealthStatusUtil.Level.B:
                    toolStripLabelLevel.Image = Properties.Resources.level_B_32;
                    break;
                case HealthStatusUtil.Level.C:
                    toolStripLabelLevel.Image = Properties.Resources.level_C_32;
                    break;
                case HealthStatusUtil.Level.D:
                    toolStripLabelLevel.Image = Properties.Resources.level_D_32;
                    break;
                case HealthStatusUtil.Level.E:
                    toolStripLabelLevel.Image = Properties.Resources.level_E_32;
                    break;
                case HealthStatusUtil.Level.F:
                    toolStripLabelLevel.Image = Properties.Resources.level_F_32;
                    break;
                case HealthStatusUtil.Level.G:
                    toolStripLabelLevel.Image = Properties.Resources.level_G_32;
                    break;
            }
        }

        private void UpdateChart(ChartType chartType)
        {
            switch (chartType)
            {
                case ChartType.Normal:
                    UpdateNormal();
                    break;

                case ChartType.Histogram:
                    chartPanel1.Visible = true;
                    chartPanel2.Visible = false;
                    chartPanel1.Dock = DockStyle.Fill;
                    chartPanelBottom.Visible = false;
                    ChartUtil.ShowChart(chartType, chartPanel1, null);
                    break;

                case ChartType.Line:
                    chartPanel1.Visible = true;
                    chartPanel2.Visible = false;
                    chartPanel1.Dock = DockStyle.Fill;
                    chartPanelBottom.Visible = false;
                    ChartUtil.ShowChart(chartType, chartPanel1, null);
                    break;

                case ChartType.Pie:
                    UpdatePie();
                    break;
            }
        }

        private void UpdateNormal()
        {
            //统计
            decimal de = 0, de2 = 0;
            foreach (BankField f in bankField.FindAll(bf => { return bf.Balance > 0; }))
                de += f.Balance;

            linkLabelBalance.Text = de.ToString();
            foreach (BankField f in bankField.FindAll(bf => { return bf.Credit > 0; }))
                de2 += f.AvailableCredit();

            linkLabelCredit.Text = de2.ToString();


            if (configMoney.CappedAmount == 0)
                labelCappedAmount.Text = (de + de2).ToString();
            else
            {
                de = 0;
                foreach (EntryField field in entryField.FindAll(ef => { return ef.Money < 0 && ef.Date.Year == DateTime.Now.Year && ef.Date.Month == DateTime.Now.Month; }))
                    de += field.Money;

                de = configMoney.CappedAmount + de;
                labelCappedAmount.Text = de.ToString();
                if (de > 0)
                    labelCappedAmount.ForeColor = Color.FromArgb(configMoney.PlusColor);
                else
                    labelCappedAmount.ForeColor = Color.FromArgb(configMoney.MinusColor);

               // Program.ShowPromptForm(this.components, labelCappedAmount, "亲!可用余额不多啦>_<");
            }


            de = 0; de2 = 0;
            List<EntryField> e1 = new List<EntryField>();
            List<EntryField> e2 = new List<EntryField>();
            foreach (EntryField ef in entryField)
            {
                if (ef.columnTag.Contains(LanguageUtil.贷款))
                {
                    de += ef.Money;
                    e1.Add(ef);
                }
                else if (ef.columnTag.Contains(LanguageUtil.借款))
                {
                    de2 += ef.Money;
                    e2.Add(ef);
                }
            }

            linkLabelLoan.Text = de.ToString();
            linkLabelLoan.Tag = e1;
            linkLabelRepayment.Text = de2.ToString();
            linkLabelRepayment.Tag = e2;

            //图表
            chartPanel2.Visible = false;
            chartPanel1.Visible = true;
            chartPanelBottom.Visible = true;
            chartPanelBottom.Dock = DockStyle.Left;
            chartPanel1.Dock = DockStyle.Fill;

            linkLabelBalance_LinkClicked(null, null);
        }

        private void UpdatePie()
        {
            chartPanel1.Visible = true;
            chartPanel2.Visible = true;
            chartPanelBottom.Visible = false;

            int width = chartPanel1.Parent.Width / 2;

            chartPanel1.Dock = DockStyle.Left;
            chartPanel1.Width = width;

            chartPanel2.Dock = DockStyle.Right;
            chartPanel2.Width = width;

            List<GroupField> groupIncome = new List<GroupField>();
            List<GroupField> groupExpense = new List<GroupField>();
            foreach (GroupField gf in GroupField.GetGroupField)
                if (gf.IorE)
                    groupIncome.Add(gf);
                else
                    groupExpense.Add(gf);

            List<XY> XYvalue = new List<XY>();
            foreach (GroupField gf in groupIncome)
            {
                decimal d = 0;
                foreach (EntryField f in EntryField.GetEntryField.FindAll(ef => { return ef.EntryType != KMDEntryType.Transfer && ef.GroupId == gf.Id; }))
                    d += f.Money;

                XYvalue.Add(new XY(gf.Name, d, 0));
            }
            ChartUtil.ShowChart(ChartType.Pie, chartPanel1, XYvalue);

            XYvalue.Clear();
            foreach (GroupField gf in groupExpense)
            {
                decimal d = 0;
                foreach (EntryField f in EntryField.GetEntryField.FindAll(ef => { return ef.EntryType != KMDEntryType.Transfer && ef.GroupId == gf.Id; }))
                    d += f.Money;

                XYvalue.Add(new XY(gf.Name, d, 0));
            }
            ChartUtil.ShowChart(ChartType.Pie, chartPanel2, XYvalue);
        }
        #endregion

        #region 插件调用
        /// <summary>
        /// 添加面板
        /// </summary>
        /// <param name="location">0 左  1 右</param>
        /// <returns></returns>
        internal BSE.Windows.Forms.XPanderPanel AddPanel(Location loc)
        {
            BSE.Windows.Forms.XPanderPanel panel = new BSE.Windows.Forms.XPanderPanel();

            if (loc == FCNS.KeepMoney.Location.Left)
                subPanelListRight.Controls.Add(panel);
            else
                subPanelListRight.Controls.Add(panel);

            return panel;
        }
        #endregion
    }
}